package club.yunqiang.rabbitmqapi.confirmlistener;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author 张云强
 * @date 2019/12/7
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1、创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 2、获取 Connection
        Connection connection = connectionFactory.newConnection();

        // 3、通过 Connection 获取 Channel
        Channel channel = connection.createChannel();


        // 4、声明 exchange
        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.#";
        channel.exchangeDeclare(exchangeName, "topic", true);

        // 5、声明 queue
        String queueName = "test_confirm_queue";
        channel.queueDeclare(queueName, true, false, false, null);

        // 6、绑定 exchange 和 queue
        channel.queueBind(queueName, exchangeName, routingKey);

        // 7、创建消费者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, StandardCharsets.UTF_8);
                System.out.println(String.format("消费端%s", msg));
            }
        };

        channel.basicConsume(queueName, true, defaultConsumer);
    }

}
